package com.zhang.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.lang.Result;
import com.zhang.entity.Blog;
import com.zhang.entity.Comment;
import com.zhang.entity.User;
import com.zhang.service.BlogService;
import com.zhang.service.CommentService;
import com.zhang.service.UserService;
import com.zhang.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张立松
 * @since 2023-03-31
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;
    @Autowired
    UserService userService;
    @Autowired
    CommentService commentService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1")Integer currentPage,
                       @RequestParam(required = false) String search){

        Page page = new Page(currentPage, 10);
        IPage iPage = blogService.page(page, new QueryWrapper<Blog>()
                .like(StrUtil.isNotBlank(search), "title", search).orderByDesc("created"));

        return Result.success(iPage);
    }

    @GetMapping("/get/{id}")
    public Result detail(@PathVariable("id")Long id){

        Blog blog = blogService.getById(id);
        return Result.success(blog);
    }

    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@RequestBody @Validated Blog blog){

        User user = userService.getById(ShiroUtil.getProfile().getId());
        blog.setUserId(user.getId());
        blog.setUserNickname(user.getNickname());
        blog.setUserAvatar(user.getAvatar());
        blog.setCreated(LocalDateTime.now());
        blog.setStatus(0);
        blog.setComment(0L);

        blogService.save(blog);

        return Result.success("操作成功");
    }

    //删除博客
    @RequiresAuthentication
    @PostMapping("/delete/{blogId}")
    public Result delete(@PathVariable("blogId")Long blogId){

        Blog blog = blogService.getById(blogId);
        Long loginUserId = ShiroUtil.getProfile().getId();
        //既不是博客主人也不是管理员则不能删除
        if(loginUserId.longValue() != blog.getUserId().longValue() && loginUserId.longValue() != 1l){
            return Result.fail("您没有删除权限");
        }
        blogService.removeById(blogId);
        commentService.remove(new QueryWrapper<Comment>().eq("blog_id",blogId));    //删除此博客的评论
        return Result.success("操作成功");
    }

}

